package dtaskboard.client.toolbar;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import dtaskboard.client.Constants;
import dtaskboard.client.DialogUtil;
import dtaskboard.client.service.ProjectService;
import dtaskboard.client.service.ProjectServiceAsync;

public class CreateProjectDialog extends DialogBox {
  private final TextBox projectName;

  public CreateProjectDialog() {
    this.projectName = new TextBox();

    Panel panel = new VerticalPanel();

    Label nameLabel = new Label("Nome do projeto");

    panel.add(nameLabel);
    panel.add(this.projectName);
    panel.add(new CreateProjectSubmitButton());

    super.setAnimationEnabled(true);
    super.setAutoHideEnabled(true);
    super.setHTML("Criação de projeto");
    super.setGlassEnabled(true);
    super.setModal(true);
    super.setWidget(panel);
    super.setVisible(true);
  }

  @Override
  public void show() {
    this.projectName.setText("");
    super.show();
  }

  class CreateProjectSubmitButton extends Button {
    public CreateProjectSubmitButton() {
      this.setText("Cria projeto");
      this.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          ProjectServiceAsync projectService = GWT.create(ProjectService.class);

          final CreateProjectDialog cpd = CreateProjectDialog.this;
          String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
          projectService.createProject(cpd.projectName.getText(), sessionId,
              new AsyncCallback<Void>() {

                @Override
                public void onSuccess(Void result) {
                  DialogUtil.closableDialog("Criação de projeto",
                      "Projeto criado com sucesso");
                  cpd.hide();
                }

                @Override
                public void onFailure(Throwable caught) {
                  DialogUtil.closableDialog("Erro",
                      "Nao foi possivel criar o projeto.");
                }
              });
        }
      });
    }
  }

}
